<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Exception;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Order extends Api
{

    /**
     * Order模型对象
     * @var \app\admin\model\Order
     */
    protected $model = null;
    protected $modelGoods = null;
    protected $modelAddress = null;
    protected $modelOrderAddress = null;
    protected $modelPoint = null;

    protected $noNeedLogin = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Order;
        $this->modelGoods = new \app\admin\model\Goods;
        $this->modelAddress = new \app\admin\model\Address;
        $this->modelOrderAddress = new \app\admin\model\order\Address;
        $this->modelPoint = new \app\admin\model\pickup\Point;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 订单列表
     * @return void
     */
    public function index()
    {
        $params = $this->request->get();
        try {
            $where = [
                'delivery_method' => $params['delivery_method'],
            ];

            if (!empty($params['shop_id'])) {
                $where['shop_id'] = $params['shop_id'];
            } else {
                $where['user_id'] = $this->auth->id;
            }

            if (!empty($params['status'])) {
                $where['status'] = $params['status'];
            }
            $list = $this->model->where($where)->paginate($params['page_size'] ?? 20);
            foreach ($list as $item) {
                $item['deliveryFlag'] = $item->delivery_method == 2 && $item->status == '2'; // 商家确认发货
                $item['receivingFlag'] = $item->status == '3'; // 用户确认收货
                $item['refundFlag'] = $item->status != 1; // 用户确认收货

                $item['createtime_text'] = date('Y-m-d H:i:s', $item['createtime']);
                $item['receiving_time_text'] = date('Y-m-d H:i:s', $item['receiving_time']);
                if (!empty($item['goods_image'])) {
                    // 按逗号分割字符串为数组
                    $item['goods_image_arr'] = explode(',', $item['goods_image']);
                } else {
                    // 为空时赋空数组（可选）
                    $item['goods_image'] = [];
                }
            }
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('查询成功', $list);
    }


    /**
     * 订单下单
     * @return void
     */
    public function placeOrder()
    {
        $params = $this->request->post();
        Db::startTrans();
        try {
            //是否采用模型验证
            $validate_class = '\app\admin\validate\Order';
            $validate = validate($validate_class);
            if (!$validate->check($params, [], "add")) {
                throw new Exception($validate->getError());
            }

            if ($params['delivery_method'] == 1 && empty($params['pickup_id'])) {
                throw new Exception('请选择自提点');
            } else if ($params['delivery_method'] == 2 && empty($params['address_id'])) {
                throw new Exception('请选择收货地址');
            }

            $address = $this->modelAddress->find($params['address_id']);


            $goods = $this->modelGoods->find($params['goods_id']);

            $goods->setDec('inventory', $params['goods_num']);

            $goods_total_money = $goods['price'] * $params['goods_num']; // 商品价格
            $shipping_cost = 4; // 运费
            $order_money = $goods_total_money + $shipping_cost - $params['deduct_money'];

            $order_no = date('YmdHis') . $this->auth->id . mt_rand(100, 999);
            $data = [
                'user_id' => $this->auth->id,
                'goods_id' => $params['goods_id'], // 商品id
                'deduct_money' => $params['deduct_money'], // 抵扣金额
                'goods_num' => $params['goods_num'], // 商品数量
                'delivery_method' => $params['delivery_method'], // 自提方式
                'goods_image' => $goods['images'], // 商品图片
                'goods_name' => $goods['goods_name'], // 商品名称
                'goods_price' => $goods['price'], // 商品名称
                'goods_total_money' => $goods_total_money, // 商品价格
                'shipping_cost' => $shipping_cost, // 运费
                'order_money' => $order_money, // 订单金额
                'order_no' => $order_no, // 订单金额
                'status' => 1, // 订单状态
                'shop_id' => $goods['shop_id'],
            ];

            // 自提
            if ($params['delivery_method'] == 1) {
                $data['pickup_id'] = $params['pickup_id'];
            } else if ($params['delivery_method'] == 2) {
                // 快递
                $data['address_id'] = $params['address_id'];
            }

            $orderData = $this->model->allowField(true)->create($data);

            // 自提
            if ($params['delivery_method'] == 1) {
            } else if ($params['delivery_method'] == 2) {
                // 快递
                // 创建订单地址数据
                $addressData = [
                    'order_id' => $orderData['id'],
                    'user_id' => $this->auth->id,
                    'name' => $address['name'],
                    'mobile' => $address['mobile'],
                    'province' => $address['province'],
                    'city' => $address['city'],
                    'area' => $address['area'],
                    'address' => $address['address'],
                    'longitude' => $address['longitude'],
                    'latitude' => $address['latitude'],
                ];

                $this->modelOrderAddress->allowField(true)->save($addressData);
            }


            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('下单成功', $orderData);
    }

    //    订单支付
    public function order_pay()
    {
        $params = $this->request->post();
        Db::startTrans();
        try {
            //是否采用模型验证
            $validate_class = '\app\admin\validate\Order';
            $validate = validate($validate_class);
            if (!$validate->check($params, [], "pay")) {
                throw new Exception($validate->getError());
            }

            $order = $this->model->find($params['id']);

            if ($order->status != 1) {
                throw new Exception('当前订单状态' . $order->status_text . ',不能支付');
            }

            $params['pay_time'] = time();

            if ($order->delivery_method == 1) {
                $params['status'] = 4;
            } else {
                $params['status'] = 2;
            }
            $this->model->allowField(true)->save($params, ['id' => $params['id']]);

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('支付成功');
    }

    /**
     * 确认发货
     * @return void
     */
    public function confirmDelivery()
    {
        $params = $this->request->post();
        Db::startTrans();
        try {
            //是否采用模型验证
            $validate_class = '\app\admin\validate\Order';
            $validate = validate($validate_class);
            if (!$validate->check($params, [], "confirmDelivery")) {
                throw new Exception($validate->getError());
            }

            $order = $this->model->find($params['id']);

            if ($order->delivery_method == 1) {
                throw new Exception('自提订单不能发货');
            }
            if ($order->status != 2) {
                throw new Exception('当前订单状态' . $order->status_text . ',不能发货');
            }

            $params['delivery_time'] = time();
            $params['status'] = 3;
            $this->model->allowField(true)->save($params, ['id' => $params['id']]);

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('发货成功', $order);
    }

    /**
     * 取消订单
     * @return void
     */
    public function cancel_order()
    {
        $params = $this->request->post();
        try {
            //是否采用模型验证
            $validate_class = '\app\admin\validate\Order';
            $validate = validate($validate_class);
            if (!$validate->check($params, [], "cancel")) {
                throw new Exception($validate->getError());
            }

            $order = $this->model->find($params['id']);

            if ($order->status != 1) {
                throw new Exception('当前订单状态' . $order->status_text . ',不能取消');
            }

            $params['cancel_time'] = time();
            $params['status'] = 6;
            $this->model->allowField(true)->save($params, ['id' => $params['id']]);

        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('取消订单成功');
    }

    /**
     * 确认收货
     * @return void
     */
    public function receiving()
    {
        $params = $this->request->post();
        try {
            //是否采用模型验证
            $validate_class = '\app\admin\validate\Order';
            $validate = validate($validate_class);
            if (!$validate->check($params, [], "receiving")) {
                throw new Exception($validate->getError());
            }

            $order = $this->model->find($params['id']);

            if ($order->status != 3 && $order->status != 4) {
                throw new Exception('当前订单状态' . $order->status_text . ',不能确认收货');
            }

            $params['receiving_time'] = time();
            $params['status'] = 5;
            $this->model->allowField(true)->save($params, ['id' => $params['id']]);

        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('确认收货成功', $order);
    }

    /**
     * 订单详情
     * @return void
     */
    public function info()
    {
        $params = $this->request->param();

        Db::startTrans();
        try {
            $data = $this->model->find($params['id']);
            if (!empty($data['goods_image'])) {
                // 按逗号分割字符串为数组
                $data['goods_image_arr'] = explode(',', $data['goods_image']);
            } else {
                // 为空时赋空数组（可选）
                $data['goods_image'] = [];
            }

            if ($data['delivery_method'] == 1) {
                $data['pickup'] = $this->modelPoint->find($data['pickup_id']);
            } else {
                $where = [
                    'order_id' => $params['id'],
                ];
                $data['address'] = $this->modelOrderAddress->where($where)->find();
            }

            $data['createtime_text'] = date('Y-m-d H:i:s', $data['createtime']);
            $data['receiving_time_text'] = date('Y-m-d H:i:s', $data['receiving_time']);
            $data['deliveryFlag'] = $data->delivery_method == 2 && $data->status == '2'; // 商家确认发货
            $data['receivingFlag'] = $data->status == '3'; // 用户确认收货
            $data['commentFlag'] = $data->status == '5' && $data->comment_status == 2; // 用户确认收货
            $data['refundFlag'] = $data->status != 1; // 申请售后

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('查询成功', $data);
    }

}








































